<?php

class BlogController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/blog';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			array('COutputCache + view', 'cacheID'=>'blog_view','duration'=>120, 'varyByParam'=>array('id'))
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','list','rss','search','stuff','icos','tags'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','recoveryip'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIcos()
	{
		$this->layout = '//layouts/main';
		$this->render('icos');
	}
	
	/**
	 * 以下这个方法用于更改数据库中所有ip2long的数据还原为
	 */
	public function actionRecoveryIp()
	{
		$model = Visitors::model()->findAll();
		foreach ($model as $item){
			$item->visitors_ip = long2ip($item->visitors_ip);
			
			if ($item->save())
				UtilTools::dump($item->attributes);

		}
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{

		$start = microtime();
		
		$model = $this->loadModel($id);
		
		$content = UtilTools::strSlice(strip_tags($model->arc_content),0,250);
		
		$this->meta['Description'] = $content;
		$this->meta['KeyWords'] = $model->arc_tags;
		
		$this->setMetaInfo();
        
        UtilStatistics::hitAdd($model, 'arc_hits');

		
//		$commentData = new CActiveDataProvider('Comment',array(
//			'criteria'=>array(
//					'condition'=>'com_aid = :com_aid AND com_rid IS NULL AND com_status = :com_status',
//					'order'=>'com_id DESC',
//					'params'=>array(
//						':com_aid'=>$model->arc_id,
//						':com_status'=>Comment::COMMENT_PUBLISHED
//						)
//				)
//		));
//		
//		//自动增加点击量
//		$model->arc_hits++;
//		//		$model->save();
//		$key = Yii::app()->user->getStateKeyPrefix().Yii::app()->request->getUserHostAddress().Yii::app()->user->name.$model->category->cate_id.$model->arc_id;
//// 		echo $key."<br />";
//		$key = md5($key);
//		$session = Yii::app()->session;
//		if(!isset($session[$key])){
//				
//			Visitors::model()->addArticleVisitorInfo($model->arc_id);
//			
//			if($model->save()){
//				$session[$key] = md5(time());
//			}			
//		}
//		
//		
//		$comment=new Comment;
//
//		// Uncomment the following line if AJAX validation is needed
//		// $this->performAjaxValidation($model);
//
//		if(isset($_POST['Comment']))
//		{
//			$comment->attributes=$_POST['Comment'];
//			
//			if($comment->save())
//				$this->redirect(array('view','id'=>$model->arc_id));
//		}
		
//		$visitors = Visitors::model()->getArticleVisitors($model->arc_id);		
//		
//		UtilTools::dump($visitors);
		
		$end = microtime();
		
		UtilTools::writeToFile( $end-$start );

		$this->render('view',array(
			'model'=>$model,
//			'commentData'=>$commentData,
//			'comment'=>$comment,
//			'visitors'=>$visitors
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$result = array();
		
		$model=new Article;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
		

		if(isset($_POST['Article']))
		{
			
// 			UtilHelper::writeToFile($_REQUEST);
			
// 			UtilHelper::dump($_REQUEST);
			
			$model->attributes=$_POST['Article'];
			$model->arc_ctype = Category::CONTENT_STORY;
			$model->arc_cid = $_POST['Article']['arc_cids'];
			$model->arc_created = $_POST['Article']['arc_created']?strtotime($_POST['Article']['arc_created']):time();
			
// 			UtilHelper::writeToFile($model->attributes,'a+');
			
// 			UtilHelper::dump($model->attributes);
			
			if($model->save()){
				$result = array(
						'state'=>'success',
						'message'=>'文章已经正常发布',
						'redirect'=>$this->createUrl('view', array('id'=>$model->arc_id))
					);
			}else{
				$result = array(
						'state'=>'fail',
						'message'=>'文章发布失败，请稍后从草稿箱中再试',
						'adds'=>CHtml::errorSummary($model),
						'redirect'=>$this->createUrl('/blog/')
					);
			}
			
			echo json_encode($result);

			Yii::app()->end();
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{
			$model->attributes=$_POST['Article'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->arc_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->meta['Description'] = '在这里记录下我个人的关于语言(英语，日语)、编程(PHP,Java,Python,C)，及其他方面学习日志，收录我平时的心情寄语、思想感悟、教学心得、读书体会，以及各类有用的资源';
		$this->meta['KeyWords'] = '语言(英语，日语)、编程(PHP,Java,Python,C),学习日志,心情寄语,思想感悟，教学心得，读书体会';
		
		$this->setMetaInfo();
		
		   $criteria = new CDbCriteria(array(
	            'condition'=>'arc_state ='.Article::STATUS_PUBLISHED,
	            'order' => 'arc_id DESC'
	       ));
			$dataProvider=new CActiveDataProvider('Article',array(
				'criteria'=>$criteria,
				'pagination'=>array(
					'pageSize'=>10
				)
			));	


		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	public function actionStuff()
	{
		$criteria = new CDbCriteria(array(
            'condition'=>"arc_state = :arc_state",
            'order'=>'arc_created DESC',
			'params'=>array(
				':arc_state' => Article::STATUS_PUBLISHED
			)
        ));
        
//        $criteria->addCondition('arc_state = '.Article::STATUS_PUBLISHED);
        
		$dataProvider=new CActiveDataProvider('Article',array(
            'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>50
			)
        ));
        
		$this->render('stuff',array(
			'dataProvider'=>$dataProvider,
		)); 
	}
    
    public function actionList()
    {
    	
    	if(!isset($_GET['id']))
            throw new CHttpException(404,'The request page doesn\'t exist');
            
    	$category = Category::model()->findByPk($_GET['id']);
    	
    	$this->meta['Description'] = $category->cate_des;
		$this->meta['KeyWords'] = $category->cate_name;
		
		$this->setMetaInfo();
    	

            
        $id = $_GET['id'];
    
        $criteria = new CDbCriteria(array(
            'condition'=>"arc_cid like '%,{$id}' OR arc_cid like '%,{$id},' OR arc_cid like '%{$id},' OR arc_cid = '{$id}'",
            'order'=>'arc_created DESC',
        ));
        
        $criteria->addCondition('arc_state = '.Article::STATUS_PUBLISHED);
        
		$dataProvider=new CActiveDataProvider('Article',array(
            'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>10
			)
        ));
        
		$this->render('list',array(
			'model'=>$category,
			'dataProvider'=>$dataProvider,
		));        
    }
    
    public function actionRss()
    {
    	$rss = new RSS(Yii::app()->name, Yii::app()->request->hostInfo, Settings::model()->getItemByKey('secondName')->set_value);
 		
		$model = Article::model()->findAll(array(
			'condition'=>'arc_state = :arc_state',
			'order'=>'arc_created DESC',
			'limit'=>20,
			'params'=>array(
				':arc_state'=>Article::STATUS_PUBLISHED
			)
		));  

		foreach ($model as $item)
		{
			$rss->AddItem($item->arc_title, Yii::app()->request->hostInfo.$this->createUrl('blog/view',array('id'=>$item->arc_id,'t'=>$item->arc_title)), UtilTools::strSlice($item->arc_content,0,500).CHtml::link('点击查看原文',Yii::app()->request->hostInfo.$this->createUrl('site/view',array('id'=>$item->arc_id,'t'=>$item->arc_title))), date(DATE_RSS,$item->arc_created));
		}
		$rss->Display();
    }
    
    public function actionTags()
    {
    	$tag = urldecode($_GET['tag']);
    	
    	if(!isset($tag))
    		throw new CHttpException(404,'The requested page does not exist.');
    	
    	$this->meta['Description'] = '本站关于标签为“'.$tag.'”的博文';
    	$this->meta['KeyWords'] = $tag;
    	
    	$this->setMetaInfo();
    	
    	$criteria = new CDbCriteria();

    	$criteria->addSearchCondition('arc_tags',$tag);
    	
    	
    	
    	$dataProvider=new CActiveDataProvider('Article',array(
    			'criteria'=>$criteria,
    			'pagination'=>array(
    					'pageSize'=>20
    			)
    	));
    		
    	$this->render('tags',array(
    			'dataProvider'=>$dataProvider
    	));
    }
    
    public function actionSearch()
    {
    	if(!isset($_GET['s']))
    		throw new CHttpException(404,'The requested page does not exist.');

    	$this->meta['Description'] = '本站关于“'.$_GET['s'].'”的搜索结果';
		$this->meta['KeyWords'] = $_GET['s'];
		
		$this->setMetaInfo();
		
    	$criteria = new CDbCriteria();	

    	$criteria->addSearchCondition('arc_title',$_GET['s']);
    	$criteria->addSearchCondition('arc_content',$_GET['s'],true,'OR');

	    	

		$dataProvider=new CActiveDataProvider('Article',array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>20
			)
		));
			
		$this->render('search',array(
	    	'dataProvider'=>$dataProvider
	    ));

    }
    
    
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Article('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Article']))
			$model->attributes=$_GET['Article'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$sql = "SELECT * FROM {{article}} WHERE arc_id = '".$id."'";
		$dependency = new CDbCacheDependency($sql);
		$model=Article::model()->cache(600,$dependency)->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='article-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
